#!/usr/bin/ruby
$:.unshift File.join(File.dirname(__FILE__))
require 'AWS/EC2'
require 'basic_configuration'
require 'aws_context'
require 'pp'
	
# Add image attributes
if ARGV[0] == '-?' || ARGV.size != 1 then
  puts "usage: make-image-public image-id|image-name"
  exit 1
end
name = ARGV[0]
filter = Regexp.new(name)

Signal.trap("INT") do
  exit 2
end

config = BasicConfiguration.new
ec2 = AwsContext.instance.ec2(*config.keys)
begin
  if name =~ /^ami-/
    image_id = name
  else
    images = ec2.describe_images
    #pp images
    matches = []
    images.each do |i|
      if i[:location] =~ filter
        matches <<  i[:id]
      end
    end
    if matches.size < 1
      puts "no image #{name}"
      exit 1
    end
    if matches.size > 1
      puts "multiple images #{name}"
      exit 1
    end
    image_id = matches[0]
  end
  res = ec2.modify_image_attribute(image_id, 'launchPermission', 'add', 
    {'UserGroup' => 'all'})
rescue
  puts "error #{$!} #{name}"
  exit 1
end

